from bottle import Bottle, static_file
from utils.common import get_resource_path
import os


index_app = Bottle()  # 子应用，不是 Blueprint
# 定义常见的 MIME 类型映射
MIME_TYPES = {
    ".js": "application/javascript",
    ".css": "text/css",
    ".json": "application/json",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "image/svg+xml",
}


@index_app.route("/")
def index():
    return static_file("index.html", root=get_resource_path("gui/dist"))


@index_app.route("/<filepath:path>")
def server_static(filepath):
    """
    配置静态路由 css  js  不存在扩展统一返回index.html

    Args:
        filepath (str): 请求的文件路径

    Returns:
        file: 静态文件或index.html
    """
    resource_path = get_resource_path("gui/dist")

    _, ext = os.path.splitext(filepath)
    mimetype = MIME_TYPES.get(ext.lower())

    if ext:
        if mimetype:
            return static_file(filepath, root=resource_path, mimetype=mimetype)
        else:
            return static_file(filepath, root=resource_path)
    else:
        return static_file("index.html", root=resource_path)
